<template>
  <view class="error-boundary">
    <view v-if="hasError" class="error-container">
      <view class="error-icon">⚠️</view>
      <text class="error-title">页面出现错误</text>
      <text class="error-message">{{ errorMessage }}</text>
      <button class="retry-btn" @click="handleRetry">重新加载</button>
    </view>
    <slot v-else></slot>
  </view>
</template>

<script>
export default {
  name: 'ErrorBoundary',
  data() {
    return {
      hasError: false,
      errorMessage: '',
      errorInfo: null
    }
  },
  methods: {
    handleError(error, errorInfo) {
      console.error('ErrorBoundary caught an error:', error, errorInfo)
      
      this.hasError = true
      this.errorMessage = error.message || '未知错误'
      this.errorInfo = errorInfo
      
      // 可以在这里上报错误到监控系统
      this.reportError(error, errorInfo)
    },
    
    handleRetry() {
      this.hasError = false
      this.errorMessage = ''
      this.errorInfo = null
      
      // 触发重新渲染
      this.$forceUpdate()
    },
    
    reportError(error, errorInfo) {
      // 这里可以集成错误上报服务
      // 例如：Sentry、Bugsnag等
      console.log('Error reported:', {
        error: error.message,
        stack: error.stack,
        componentStack: errorInfo?.componentStack,
        timestamp: new Date().toISOString()
      })
    }
  },
  
  // Vue 2 错误处理
  errorCaptured(error, vm, info) {
    this.handleError(error, { componentStack: info })
    return false // 阻止错误继续传播
  },
  
  // Vue 3 错误处理
  onErrorCaptured(error, instance, info) {
    this.handleError(error, { componentStack: info })
    return false
  }
}
</script>

<style scoped>
.error-boundary {
  min-height: 200rpx;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 80rpx 40rpx;
  text-align: center;
}

.error-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.error-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 16rpx;
}

.error-message {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.retry-btn {
  background: var(--primary-color, #C6282B);
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  cursor: pointer;
  transition: all 0.3s;
}

.retry-btn:hover {
  opacity: 0.8;
}
</style> 